js判断一个变量是否是常量
时间: 2023-01-11 14:55:36 浏览: 93
在 JavaScript 中可以使用 `Object.defineProperty()` 来判断一个变量是否是常量。
例如:
```
const MY_CONSTANT = 'hello';
Object.defineProperty(window, 'MY_CONSTANT', {
get: function() { return MY_CONSTANT; },
set: function(value) {
throw new Error("Cannot assign to a constant");
}
});
```
在上面的例子中,我们使用 `Object.defineProperty()` 定义了一个常量 `MY_CONSTANT`,并且在尝试修改它时抛出了一个错误。这样,我们就可以判断一个变量是否是常量了。
另外,JavaScript 也支持使用 `const` 关键字来声明常量。但是,这种方法仅适用于在严格模式下使用。
例如:
```
"use strict";
const MY_CONSTANT = 'hello';
MY_CONSTANT = 'world'; // Uncaught TypeError: Assignment to constant variable.
```
在上面的例子中,使用 `const` 关键字声明的常量在尝试修改时会抛出一个错误。
相关问题
使用js实现一个贪吃蛇
由于本AI不支持图形界面,因此我提供的是一个控制台版本的贪吃蛇游戏。
```javascript
const readline = require('readline');
// 定义方向常量
const UP = 0;
const RIGHT = 1;
const DOWN = 2;
const LEFT = 3;
// 定义游戏配置
const ROWS = 30; // 行数
const COLS = 50; // 列数
const SPEED = 200; // 蛇移动速度(毫秒)
// 定义游戏变量
let snake = [[1, 1], [1, 2], [1, 3]]; // 蛇的初始位置
let direction = RIGHT; // 蛇的初始方向
let food = null; // 食物位置
// 定义游戏状态
let isGameOver = false;
let score = 0;
// 初始化游戏
function init() {
// 随机放置食物
food = [Math.floor(Math.random() * ROWS), Math.floor(Math.random() * COLS)];
// 清空控制台
console.clear();
// 输出游戏界面
console.log(`Score: ${score}`);
for (let i = 0; i < ROWS; i++) {
let row = '';
for (let j = 0; j < COLS; j++) {
if (i === food[0] && j === food[1]) {
row += 'F'; // 食物
} else if (isSnake(i, j)) {
row += 'S'; // 蛇
} else {
row += '.'; // 空地
}
}
console.log(row);
}
}
// 判断一个位置是否是蛇身
function isSnake(row, col) {
for (let i = 0; i < snake.length; i++) {
if (snake[i][0] === row && snake[i][1] === col) {
return true;
}
}
return false;
}
// 处理用户输入
function handleInput(input) {
switch (input) {
case 'w':
if (direction !== DOWN) {
direction = UP;
}
break;
case 'd':
if (direction !== LEFT) {
direction = RIGHT;
}
break;
case 's':
if (direction !== UP) {
direction = DOWN;
}
break;
case 'a':
if (direction !== RIGHT) {
direction = LEFT;
}
break;
}
}
// 移动蛇
function moveSnake() {
// 根据方向移动蛇头
let head = [...snake[0]];
switch (direction) {
case UP:
head[0]--;
break;
case RIGHT:
head[1]++;
break;
case DOWN:
head[0]++;
break;
case LEFT:
head[1]--;
break;
}
// 如果撞到墙或自己的身体,游戏结束
if (head[0] < 0 || head[0] >= ROWS || head[1] < 0 || head[1] >= COLS || isSnake(head[0], head[1])) {
isGameOver = true;
return;
}
// 如果吃到食物,蛇变长
if (head[0] === food[0] && head[1] === food[1]) {
score++;
snake.unshift(head);
food = [Math.floor(Math.random() * ROWS), Math.floor(Math.random() * COLS)];
} else {
// 否则蛇移动一格
snake.pop();
snake.unshift(head);
}
}
// 主循环
async function mainLoop() {
while (!isGameOver) {
// 等待用户输入
let input = await new Promise(resolve => {
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.once('keypress', (_, key) => {
resolve(key.name);
});
});
handleInput(input);
moveSnake();
init();
await new Promise(resolve => setTimeout(resolve, SPEED));
}
console.log(`Game over! Score: ${score}`);
}
// 启动游戏
mainLoop();
```
用js写一个贪吃蛇
好的,以下是一个简单的 JavaScript 贪吃蛇游戏:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇游戏</title>
<style>
#game-board {
width: 400px;
height: 400px;
border: 1px solid black;
}
.snake {
width: 20px;
height: 20px;
background-color: green;
position: absolute;
}
.food {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="game-board"></div>
<script src="snake.js"></script>
</body>
</html>
```
JavaScript 代码:
```javascript
// 定义常量
const boardWidth = 20; // 游戏区域宽度
const boardHeight = 20; // 游戏区域高度
const cellWidth = 20; // 蛇身格子宽度
const cellHeight = 20; // 蛇身格子高度
const initialSnakeLength = 3; // 蛇初始长度
const moveInterval = 100; // 蛇移动时间间隔(毫秒)
// 获取游戏区域元素和分数元素
const gameBoard = document.querySelector("#game-board");
const scoreElement = document.createElement("div");
scoreElement.innerText = "分数:0";
gameBoard.appendChild(scoreElement);
// 定义变量
let snake = []; // 蛇的身体,数组中的元素为坐标对象 {x, y}
let food = null; // 食物的坐标对象 {x, y}
let direction = "right"; // 移动方向
let score = 0; // 分数
// 初始化游戏区域
for (let i = 0; i < boardHeight; i++) {
for (let j = 0; j < boardWidth; j++) {
const cell = document.createElement("div");
cell.style.width = cellWidth + "px";
cell.style.height = cellHeight + "px";
cell.style.position = "absolute";
cell.style.top = i * cellHeight + "px";
cell.style.left = j * cellWidth + "px";
gameBoard.appendChild(cell);
}
}
// 初始化蛇
for (let i = 0; i < initialSnakeLength; i++) {
snake.push({ x: i, y: 0 });
}
// 初始化食物
generateFood();
// 开始游戏循环
setInterval(() => {
// 移动蛇
const head = getNextHead();
if (isDead(head)) {
alert("游戏结束,分数:" + score);
location.reload();
return;
}
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
scoreElement.innerText = "分数:" + score;
generateFood();
} else {
snake.pop();
}
// 更新蛇身体的位置
const snakeElements = document.querySelectorAll(".snake");
snake.forEach((cell, index) => {
const snakeElement = snakeElements[index];
snakeElement.style.top = cell.y * cellHeight + "px";
snakeElement.style.left = cell.x * cellWidth + "px";
});
// 更新食物的位置
const foodElement = document.querySelector(".food");
foodElement.style.top = food.y * cellHeight + "px";
foodElement.style.left = food.x * cellWidth + "px";
}, moveInterval);
// 监听键盘事件,控制蛇的移动方向
document.addEventListener("keydown", (event) => {
switch (event.key) {
case "ArrowUp":
if (direction !== "down") {
direction = "up";
}
break;
case "ArrowDown":
if (direction !== "up") {
direction = "down";
}
break;
case "ArrowLeft":
if (direction !== "right") {
direction = "left";
}
break;
case "ArrowRight":
if (direction !== "left") {
direction = "right";
}
break;
}
});
// 生成食物的随机位置
function generateFood() {
while (true) {
const x = Math.floor(Math.random() * boardWidth);
const y = Math.floor(Math.random() * boardHeight);
if (!snake.some((cell) => cell.x === x && cell.y === y)) {
food = { x, y };
const foodElement = document.createElement("div");
foodElement.className = "food";
foodElement.style.top = y * cellHeight + "px";
foodElement.style.left = x * cellWidth + "px";
gameBoard.appendChild(foodElement);
break;
}
}
}
// 获取蛇下一步的头部坐标
function getNextHead() {
const currentHead = snake[0];
let nextHead;
switch (direction) {
case "up":
nextHead = { x: currentHead.x, y: currentHead.y - 1 };
break;
case "down":
nextHead = { x: currentHead.x, y: currentHead.y + 1 };
break;
case "left":
nextHead = { x: currentHead.x - 1, y: currentHead.y };
break;
case "right":
nextHead = { x: currentHead.x + 1, y: currentHead.y };
break;
}
return nextHead;
}
// 判断蛇是否死亡
function isDead(head) {
return (
head.x < 0 ||
head.x >= boardWidth ||
head.y < 0 ||
head.y >= boardHeight ||
snake.some((cell) => cell.x === head.x && cell.y === head.y)
);
}
```
现在你可以在浏览器中打开 HTML 文件运行游戏了。