gpt4 book ai didi

Javascript - 如何找到变量的名称而不是它所保存的值

转载 作者:行者123 更新时间:2023-12-03 05:46:30 26 4
gpt4 key购买 nike

我有这个函数来设置立方体在 Canvas 上的移动(随机),everyVar 是将要使用的变量,a,b,c,d是 +、-、*、/的函数(抱歉,如果它令人困惑)。有没有办法找到变量的名称而不是它所保存的值;我有“user.s = a(b(c(d(r, 2), e), w), q);”,我需要一种方法将其放入重复函数中,以便变量保持不变,但信息更新,但如果我把它放在其他地方,它就会有不同的变量。我不能只设置另一个变量,如 myVariable = q ,因为它将保存数字而不是变量本身(例如,我需要它说 user.y 而不是 300)。请让您的答案尽可能简单,因为您可能知道我是初学者。

function setMovement(user){
var everyVar = [user.x, user.y, user.direction, user.distance]

var q = everyVar[Math.floor(Math.random()*everyVar.length)];
var w = everyVar[Math.floor(Math.random()*everyVar.length)];
var e = everyVar[Math.floor(Math.random()*everyVar.length)];
var r = everyVar[Math.floor(Math.random()*everyVar.length)];

user.s = a(b(c(d(r, 2), e), w), q);

a = operators[Math.floor(Math.random()*operators.length)]
b = operators[Math.floor(Math.random()*operators.length)]
c = operators[Math.floor(Math.random()*operators.length)]
d = operators[Math.floor(Math.random()*operators.length)]
}

最佳答案

这里是一些您可以使用的代码:

// Define the operators as functions
var operators = [
function add(x, y) { return x + y },
function sub(x, y) { return x - y },
function mul(x, y) { return x * y },
function div(x, y) { return x / y }
];

// Don't reference the values, but the property names
var everyVar = ['x', 'y', 'direction', 'distance'];

function setMovement(user){
var q = everyVar[Math.floor(Math.random()*everyVar.length)];
var w = everyVar[Math.floor(Math.random()*everyVar.length)];
var e = everyVar[Math.floor(Math.random()*everyVar.length)];
var r = everyVar[Math.floor(Math.random()*everyVar.length)];

var a = operators[Math.floor(Math.random()*operators.length)]
var b = operators[Math.floor(Math.random()*operators.length)]
var c = operators[Math.floor(Math.random()*operators.length)]
var d = operators[Math.floor(Math.random()*operators.length)]

// Make s a function, so the expression is evaluated with the
// current values of the user object properties:
user.s = function () {
return a(b(c(d(user[r], 2), user[e]), user[w]), user[q]);
};
// For debugging, you can use this extra property to see
// which expression the "random" function evaluates:
user.s.description = `${a.name}(${b.name}(${c.name}(${d.name}` +
`(user.${r}, 2), user.${e}), user.${w}), user.${q})`;
}

// same data
var user = {
x: 20,
y: 10,
direction: 1,
distance: 5
}
// Define "random" function user.s
setMovement(user);

console.log( 'user.s() evaluates this expression:\n', user.s.description );

console.log( 'result of user.s():', user.s() );

// Change x and y and display result then:
user.x -= 5;
user.y += 10;
console.log( 'result of user.s():', user.s() );

注意:小心除法:当第二个参数为 0 时,您将收到运行时错误。

关于Javascript - 如何找到变量的名称而不是它所保存的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40316820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com