Javascript数组变量作为属性

时间:2014-04-04 23:31:08

标签: javascript arrays

如果我将一个数组作为属性访问,我是否仍然可以通过声明theArray [index]来访问它的内部索引?

这是我的代码:

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函数中,我想访问Dictionary的属性" theWords"。我这样说的是

var theDictionary = new Dictionary();
var articles = theDictionary.theWords[0];

这可能吗?此外,我可以访问数组中的特定索引"文章"通过这样的话来说:

var article1 = theDictionary.theWords[0][0];

这可能吗?我的代码给了我一个错误,但我不确定是什么问题。

1 个答案:

答案 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());