我有一个像这样的JavaScript对象数组:
var myArray = [{...}, {...}, {...}];
Run Code Online (Sandbox Code Playgroud)
每个对象id在其他属性中都是唯一的:
{
id: 4,
property1: 'something',
property2: 'something'
}
Run Code Online (Sandbox Code Playgroud)
如果我只知道它的id属性,我如何获得该数组中特定对象的索引?所以,如果我知道,myArray[x].id == 4我怎么能找到x?
为什么这段代码有效......
var message = {
texts: {
text1: 'Hello',
text2: 'World'
},
greet: function() {
console.log(this.texts.text1 + ' ' + this.texts.text2 + '!');
}
}
message.greet();
Run Code Online (Sandbox Code Playgroud)
......但这不是吗?
var message = {
texts: {
text1: 'Hello',
text2: 'World'
},
both: this.texts.text1 + ' ' + this.texts.text2 + '!',
greet: function() {
console.log(this.both);
}
}
message.greet();
Run Code Online (Sandbox Code Playgroud)
它给了我"两个都没有定义"的错误.我在这里错过了什么?出了点问题this.both?对于对象文字,我总是新手