Javascript数组变量作为属性
如果我访问一个数组作为属性,我仍然可以通过说数组[index]来访问它的内部索引吗 以下是我的代码:Javascript数组变量作为属性,javascript,arrays,Javascript,Arrays,如果我访问一个数组作为属性,我仍然可以通过说数组[index]来访问它的内部索引吗 以下是我的代码: function Dictionary() { var articles, verbs, nouns, prepositions, adjectives, words; articles = ["the", "a"]; verbs = ["shoot", "break", "amaze", "grope", "destroy", "bark", "stream", "fl
function Dictionary() {
var articles, verbs, nouns, prepositions, adjectives, words;
articles = ["the", "a"];
verbs = ["shoot", "break", "amaze", "grope", "destroy", "bark", "stream", "flow"];
nouns = ["journal", "bird", "library", "book", "calculator", "pen", "evening"];
prepositions = ["while", "although", "beside", "by", "in", "outside", "like", "into"];
adjectives = ["white", "black", "blue", "red", "bright", "calm", "cheerful", "clumsy", "cloudy"];
words = [articles, verbs, nouns, prepositions, adjectives];
Object.defineProperties(this, {
"theWords": {
get: function() {return words;}
},
"theArticles": {
get: function() {return articles;}
},
"theVerbs": {
get: function() {return verbs;}
},
"theNouns": {
get: function() {return nouns;}
},
"thePrepositions": {
get: function() {return prepositions;}
},
"theAdjectives": {
get:function() {return adjectives;}
}
});
}
在另一个名为Poem的Javascript函数中,我想访问字典的属性“theWords”。我是这样说的
var theDictionary = new Dictionary();
var articles = theDictionary.theWords[0];
这可能吗?此外,我可以通过如下方式访问数组“articles”中的特定索引:
var article1 = theDictionary.theWords[0][0];
这可能吗?我的代码给了我一个错误,但我不确定哪里出了问题。我会这样做:
function Dictionary(user){
/* It's less code to write `var` repeatedly than the variable name twice
in this case. You can save keystrokes, avoid pressing shift, by using
single quotes. That does not mean your code was not clear or didn't work
*/
this.currentUser = user;
this.articles = ['the', 'a'];
this.verbs = ['shoot', 'break', 'amaze', 'grope', 'destroy', 'bark', 'stream', 'flow'];
this.nouns = ['journal', 'bird', 'library', 'book', 'calculator', 'open', 'evening'];
this.prepositions = ['while', 'although', 'beside', 'by', 'in', 'outside', 'like', 'into'];
this.adjectives = ['white', 'black', 'blue', 'red', 'bright', 'calm', 'cheerful', 'clumsy', 'cloudy'];
this.words = [this.articles, this.verbs, this.nouns, this.prepositions, this.adjectives];
// you don't really need this function - just an example of a Constructor function
this.wordsToString = function(){
var wds = this.words, a = [];
for(var i in wds){
a.concat(wds[i])
}
return a.join();
}
}
var dic = new Dictionary('Bob');
console.log(dic.currentUser); console.log(dic.articles[0]);
console.log(dic.wordsToString());
现在,您可以更改articles
属性或其他任何内容:
dic.articles = ['test1', 'test2'];
console.log(dic.wordsToString());
它给出了什么错误?你的代码对我有效。您是否在旧版本的IE上使用此功能(或在IE上以兼容模式使用)?IE8带来了对
Object.defineProperty
的一些支持,但仅限于DOM原型。我还记得在要求某些项在描述符中显式时过于严格,但我可能弄错了。同样,我们真的需要这里的错误。