JavaScript-无法更新嵌套的For循环内的数组对象属性

时间:2018-09-22 00:13:16

标签: javascript arrays for-loop

我有以下嵌套循环:

for(var i = 0; i < availabilities.length; i++){
    if(availabilities[i].round === 1){
        //  Return the indices of all objects which share the same event_team_user_id property
        var indices = helperService.findArrayIndices(availabilities, 'event_team_user_id', availabilities[i].event_team_user_id);
        for(var x = 1; x < indices.length; x++){
            availabilities[x].status = availabilities[i].status;
            console.log(availabilities[x]);
        }
    }
}
console.log(availabiities);

上面的代码应该找到与特定回合相关联的所有数组对象(在本例中为第1轮),然后更新所有其他数组对象的status属性以匹配第一回合的状态(如果这些数组对象具有相同的 event_team_user_id < / em>属性。

嵌套在两个循环中的

console.log(availabilities[x]);正确输出了数组对象,但是console.log(availabiities);返回了一个数组对象,其中在for循环中对 status 属性所做的更改没有反映出来。

为什么不保存数组对象中的更新属性?

2 个答案:

答案 0 :(得分:2)

如果我们假设for是因为您已经提到打印问题而打出错误,则表明您输入的第二个indices循环可能有问题。您没有使用helperService返回的indices[x]。您应该执行availabilities来访问x的正确索引,并且let availabilities = [ { round: 1, event_team_user_id: 1, status: 'shouldmatch' }, { round: 2, event_team_user_id: 2, status: 'shouldnotchange' }, { round: 3, event_team_user_id: 1, status: 'shouldchange', }, { round: 4, event_team_user_id: 3, status: 'shouldnotchange', }, { round: 5, event_team_user_id: 1, status: 'shouldchange' } ]; for(var i = 0; i < availabilities.length; i++){ if(availabilities[i].round === 1){ // Return the indices of all objects which share the same event_team_user_id property var indices = [2, 4]; for(var x = 0; x < indices.length; x++){ const curr = indices[x]; availabilities[curr].status = availabilities[i].status; } } } console.log(availabilities);应该从0开始。

import cloudstorage

答案 1 :(得分:0)

看起来像错了错字

之前

SELECT
    p1.id,
    p1.post_title,
    p1.post_name,
    COALESCE(p2.post_title, 'NA') AS brand_title,
    COALESCE(p2.post_name, 'NA') AS brand_name,
    COALESCE(p3.post_title, 'NA') AS size_title,
    COALESCE(p3.post_name, 'NA') AS size_name
FROM posts p1
LEFT JOIN
(
    SELECT
        post_id,
        MAX(CASE WHEN meta_key = 'basicBrandName' THEN meta_value END) AS idBrand,
        MAX(CASE WHEN meta_key = 'basicSize' THEN meta_value END) AS idSize
    FROM postmeta
    GROUP BY post_id
) pm
    ON p1.id = pm.post_id
LEFT JOIN posts p2
    ON pm.idBrand = p2.id
LEFT JOIN posts p3
    ON pm.idSize = p3.id
WHERE p1.id = 758;

之后

console.log(availabiities);