有没有一种方法可以使用函数的参数通过点符号在对象内定位项目?

时间:2019-05-15 23:35:54

标签: javascript

一个例子是:

var test = {
apples: [],
oranges: [],
add: function (arrayInput) {
console.log(test.arrayInput.length)
}

根据用户在add函数中传递的内容,在哪里arrayInput可以记录苹果或橘子。这可能以某种方式出现还是点表示法不接受变量?

4 个答案:

答案 0 :(得分:3)

您可以尝试以下方法:

    var test = {
    apples: [],
    oranges: [],
    add: function (arrayInput) {
    console.log(this[arrayInput].length);
        }
    }

答案 1 :(得分:1)

您的方法应该有权使用没有this关键字的参数传递。如果要引用对象上的属性,则仅需要“ this”。答案应该是

var test = {
apples: [],
oranges: [],
add: function (arrayInput) {
console.log(arrayInput.length)
}

但是如果您想要苹果的长度,则可以使用“ this”

var test = {
apples: [],
oranges: [],
add: function (arrayInput) {
console.log(this.apples.length)
}

如果您希望arrayInput是字符串“ apples”或“ oranges”,并且希望使用该属性,则可以使用方括号表示法。

var test = {
    apples: [],
    oranges: [],
    add: function (arrayInput) {
    console.log(this[arrayInput].length)
    }

在这种情况下,您使用“ this”访问对象,括号使您可以访问字符串传递的属性。

答案 2 :(得分:1)

柯南是正确的,但是例子不是很清楚。

首先,您不能按要求使用“点符号”;您必须使用属性名称-因此this.arrayInput.length将不起作用,但是this[arrayInput].length 将会,假设“ arrayInput”是一个字符串,它引用的属性实际上是其中的一部分对象。

如果您的对象test具有元素applesoranges,则可以将这些元素作为this[param]访问。让我们看一个更好的示例-由于有一种方法add,我们可以使用它来向对象中的数组元素添加内容

var test = {
    apples: [],
    oranges: [],
    add: function (element, item) {
        this[element].push(item);
    },
    list: function (element) {
        console.log(this[element]);
    }
};

因此,您现在可以像下面的代码片段一样先进行test.add('apples', 'red delicious')test.add('granny smith')然后test.list('apples')的操作:

var test = {
    apples: [],
    oranges: [],
    add: function (element, item) {
        this[element].push(item);
    },
    list: function (element) {
        console.log(this[element]);
    }
};

test.add('apples', 'red delicious');
test.add('apples', 'granny smith');
test.add('oranges', 'navel');
test.list('apples');
test.list('oranges');

答案 3 :(得分:0)

只需使用[],因为您也可以使用[]访问对象密钥。

console.log(this[arrayInput].length);