简体   繁体   English

For循环未使用JavaScript函数中的参数

[英]For loop not using argument from JavaScript function

I'm trying to run this function in my server.js file: 我正在尝试在我的server.js文件中运行此功能:

function formatArr (targetArr, characteristic, formattedArr) {
    console.log(characteristic);
    for (var i = 0; i < targetArr.length; i++) {
        formattedArr.push({characteristic:targetArr[i]})
    };
    return formattedArr;
};

If I call it like so: 如果我这样称呼它:

var targetSize = Object.keys(JSON.parse(req.query.size)); //[s,m,l]
var sizeKey = "size";
// format size array for mongodb query 
var formattedSize = [];
var formattedSize = formatArr(targetSize, sizeKey, formattedSize);
console.log(formattedSize);

it DOES console log "size", but it does NOT replace the word characteristic with the word size in the formattedSize array. 它不会控制台日志“大小”,但不会用formattedSize数组中的单词大小替换单词特征。 Here's what I get in my server console: 这是我在服务器控制台中得到的:

size
[ { characteristic: 's' },{ characteristic: 'm' },{ characteristic: 'l' } ]

How do I make it replace characteristic with size within the array? 如何使阵列中的特征替换特征? This is my desired output: 这是我想要的输出:

size
[ { size: 's' },{ size: 'm' },{ size: 'l' } ]

I want to be able to reuse the formatArr function with other characteristics. 我希望能够重用具有其他特征的formatArr函数。

You should use bracket notation for variable property names: 您应该对可变属性名称使用括号符号

function formatArr (targetArr, characteristic, formattedArr) {
    console.log(characteristic);
    for (var i = 0; i < targetArr.length; i++) {
        var obj = {};
        obj[characteristic] = targetArr[i];
        formattedArr.push(obj);
    };
    return formattedArr;
};

A little verbose but still. 有点冗长,但仍然。 If you are in ES2015 friendly environment you can use shorter syntax: 如果您在ES2015友好环境中,则可以使用较短的语法:

for (var i = 0; i < targetArr.length; i++) {
    formattedArr.push({[characteristic]: targetArr[i]});
};

Try this: 尝试这个:

function formatArr (targetArr, characteristic, formattedArr) {
    for (var i = 0; i < targetArr.length; i++) {
        var obj = {};
        obj[characteristic:targetArr] = targetArr[i]
        formattedArr.push(obj)
    };
    return formattedArr;
};

In very new JavaScript environments, you can write: 在非常新的JavaScript环境中,您可以编写:

    formattedArr.push({ [characteristic]: targetArr[i] })

Otherwise, you'll have to build an object step-by-step as in @dfsq's answer. 否则,您将必须按照@dfsq的答案逐步构建对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM