我是JavaScript的新手,刚刚遇到了这个问题.无法通过谷歌搜索和搜索stackoverflow来解决它.代码段如下:
var a = { n : 1};
var b = a;
a.x = a = {n: 2};
console.log(a.x);
console.log(b.x);Run Code Online (Sandbox Code Playgroud)
根据我目前的知识,a.x = a = {n:2};等于:
a = {n : 2};
a.x = a;Run Code Online (Sandbox Code Playgroud)
这最终使得等于{n:2, x:{n:2}}.所以a.x应该等于{n:2},因为b = a,所以b.x = {n:2}.但是我在浏览器中运行的结果是:alert(a.x)是undefined和alert(b.x)是[object object].
有人可以解释原因吗?非常感谢.
任何人都可以帮我告诉我我的Javascript代码有什么问题吗?
var a = ["zero", "one", "two", "three"];
for (var i in a) {
var sliced = a.slice(i + 1);
console.log(sliced);
}Run Code Online (Sandbox Code Playgroud)
控制台日志给出: ["one", "two", "three"],[],[],[]
但我的期望是: ["one", "two", "three"],["two", "three"],["three"],[]
那么,为什么我的代码不起作用?我该怎么编码?非常感谢.
在这篇文章中如何显示一个对象的所有方法?,它说“您可以使用 Object.getOwnPropertyNames() 来获取属于一个对象的所有属性,无论是否可枚举”。通过示例,我们可以看到所有属性都包括Math列出的对象的方法。我尝试并得到了相同的结果。
然后我尝试定义我自己的对象并以相同的方式列出它的属性,但为什么没有列出方法?例如console.log(Object.getOwnPropertyNames(animal))为什么它只返回["name", "weight"]而不包括"eat", "sleep" and wakeUp?
function Animal(name, weight) {
this.name = name;
this.weight = weight;
}
Animal.prototype.eat = function() {
return `${this.name} is eating!`;
}
Animal.prototype.sleep = function() {
return `${this.name} is going to sleep!`;
}
Animal.prototype.wakeUp = function() {
return `${this.name} is waking up!`;
}
var animal = new Animal('Kitten', '5Kg');
console.log(Object.getOwnPropertyNames(animal)); // ["name", "weight"]Run Code Online (Sandbox Code Playgroud)
另一个例子是,为什么下面的一个返回属于超类的属性,因为它是Triangle从Shape …
javascript ×3