【问题标题】:reassign a value in an array of objects in a loop does not work Javascript在循环中重新分配对象数组中的值不起作用Javascript
【发布时间】:2020-09-23 15:48:05
【问题描述】:

我有一个对象videos 并想重新分配其中的每个参数start。为了归档这个我循环了对象,但分配只在循环之外工作,这对我来说似乎很奇怪。

我试过了:

var output1 = '';
let n=videos[0].start;
n = 0;

videos.forEach((element, index) => {
  videos[n].start = n * clipLength;
  output1 += n + ': ' + videos[n].start+'; ';
  n++;
});
console.log(output1);

这导致了我想要的结果:

0: 0; 1: 2; 2: 4; 3: 6; 4: 8; 5: 10; 6: 12; 7: 14; 8: 16; 9: 18; 10: 20; 11: 22; 12: 24; 13: 26; 14: 28; 15: 30; 16: 32; 17: 34; 18: 36; 19: 38; 20: 40; 21: 42; 22: 44; 23: 46; 24: 48; 25: 50; 26: 52; 27: 54; 28: 56; 29: 58; 30: 60; 31: 62; 32: 64; 33: 66; 34: 68; 35: 70; 36: 72; 37: 74; 38: 76; 39: 78; 40: 80; 41: 82; 42: 84; 43: 86; 44: 88; 45: 90; 46: 92; 47: 94; 48: 96; 49: 98; 50: 100; 51: 102; 52: 104; 53: 106; 54: 108; 55: 110; 56: 112; 57: 114; 58: 116; 59: 118; 60: 120; 61: 122; 62: 124; 63: 126; 64: 128; 65: 130; 66: 132; 67: 134; 68: 136; 69: 138; 70: 140; 71: 142; 72: 144; 73: 146; 74: 148; 75: 150; 76: 152; 77: 154; 78: 156; 79: 158; 80: 160; 81: 162; 82: 164; 83: 166; 84: 168; 85: 170; 86: 172; 87: 174; 88: 176; 89: 178; 90: 180; 91: 182; 92: 184; 93: 186; 94: 188; 95: 190; 

但是当我在循环外检查结果时,我得到了我的旧值。

这个:

var output2 = '';

for (var property2 in videos) {
  output2 += property2 + ': ' + videos[property2].start+'; ';
}

console.log(output2);

导致:

0: 180; 1: 182; 2: 184; 3: 186; 4: 188; 5: 190; 6: 132; 7: 134; 8: 136; 9: 138; 10: 140; 11: 142; 12: 144; 13: 146; 14: 148; 15: 150; 16: 152; 17: 154; 18: 156; 19: 158; 20: 160; 21: 162; 22: 164; 23: 166; 24: 168; 25: 170; 26: 172; 27: 174; 28: 176; 29: 178; 30: 180; 31: 182; 32: 184; 33: 186; 34: 188; 35: 190; 36: 132; 37: 134; 38: 136; 39: 138; 40: 140; 41: 142; 42: 144; 43: 146; 44: 148; 45: 150; 46: 152; 47: 154; 48: 156; 49: 158; 50: 160; 51: 162; 52: 164; 53: 166; 54: 168; 55: 170; 56: 172; 57: 174; 58: 176; 59: 178; 60: 180; 61: 182; 62: 184; 63: 186; 64: 188; 65: 190; 66: 132; 67: 134; 68: 136; 69: 138; 70: 140; 71: 142; 72: 144; 73: 146; 74: 148; 75: 150; 76: 152; 77: 154; 78: 156; 79: 158; 80: 160; 81: 162; 82: 164; 83: 166; 84: 168; 85: 170; 86: 172; 87: 174; 88: 176; 89: 178; 90: 180; 91: 182; 92: 184; 93: 186; 94: 188; 95: 190; 

奇怪的是,迭代之外的 videos[0].start = 0; 非常适合我。

我尝试了几个循环语句,例如for...inforforEach,结果相同,我无法永久更改视频对象。

可能是什么原因以及如何更改 start 值?

编辑

我试图以另一种方式反对Object.assign()videos,但没有运气。会不会是因为Promise 对象,才让我在创建后无法更改值?

这是整个功能(简化为基本功能):

 module.exports.submit = (data) => {
        const schema = {
            search: Joi.string().regex(/^[a-zA-Z0-9 ]*$/).min(2).max(30).required(),
            duration: Joi.number().integer().min(1).max(100).required()
        };

    const valid = Joi.validate({
        search: data.search,
        duration: data.duration
    }, schema);


    return new Promise((resolve, reject) => {

        const minClips = parseInt(data.duration/2);
        var maxClips = data.duration;
        const clipLength = 2;
        const videoStart = 0;

        pexelsClient.searchVideos(data.search, maxClips, 1).then(function(pexels) {

            let tracks = [];
            let videos = [];


            let x = Math.round(maxClips/(3/(maxClips/100))-1)
            console.log(x+" iterations")

            for (let [index, video] of pexels.videos.entries()) {
                let videoFiles = video.video_files;
                let hdVideo = videoFiles.find(file => file.height === 720 || file.height === 1920) || videoFiles[0];

                videos[index] = {
                    asset: {
                        type: "video",
                        src: hdVideo.link,
                        trim: Math.floor(Math.random() * 6)
                    },
                    start: (maxClips*2) - (index * clipLength),
                    length: clipLength, 
                    filter: "greyscale",
                    opacity: 0.3
                };


                if (index === 0) {
                    videos[index].transition = {
                        out: "fade"
                    }
                    console.log(index)
                }

                if (index === (maxClips - 1)) {
                    videos[index].transition = {
                        in: "fade"
                    }

                }

            }

            const videoslength = Object.keys(videos).length;

            console.log("asset "+videos[0].asset)

            var output1 = '';
            var n = 0;
            for (var i = 30; i <= videoslength; i++) {
                if (n >= 30) { n=0} else {
                    const b = Object.assign({}, videos, {


                            ...videos.asset,
                            asset: videos[n].asset

                    });
                    console.log(videos[n].asset)
                    }
                output1 += n + ': ' + videos[n].start+'; ';
                n++;
            }
            console.log(output1);
            console.log("amount elements "+Object.keys(videos).length);


            var output2 = '';
            for (var property2 in videos) {
                //videos[property2].start = property2 * clipLength;
                output2 += property2 + ': ' + videos[property2].asset.src+'; ';

            }
            console.log(output2);

            tracks[0] = {
                clips: videos
            };

            let timeline = {
                soundtrack: {
                    src: shotstackAssetsUrl + "music/" + data.soundtrack,
                    effect: "fadeOut"
                },
                background: "#000000",
                tracks: tracks,
            };

            let output = {
                format: "mp4",
                resolution: "sd"
            };

            let edit = {
                timeline: timeline,
                output: output
            };

            request({
                url: shotstackUrl + 'render',
                method: 'POST',
                headers: {
                    'x-api-key': shotstackApiKey
                },
                json: true,
                body: edit
            }, function (error, response, body){
                if (error) {
                    console.log(error);
                    console.log(response);
                    return reject(error);
                }

                return resolve(body.response);
            });
        }).catch(function(error) {
            console.log(error);
            return reject(error);
        });
    });
 };

【问题讨论】:

  • 请注意,在您的第一个 sn-p 中,let n=videos[0].start; 是无用的,因为您将其覆盖在下面:n = 0;
  • edit您的问题,而不是在答案中发布代码

标签: javascript arrays loops object foreach


【解决方案1】:

您的代码有效(运行下面的代码,您将看到结果),一旦您修改了第一个循环中的值(构建 output1),那么 output2 也是正确的。

但是你必须先调用你的第一个 sn-p (output1)。原因是您实际上在第一个循环 (videos[n].start = n * clipLength;) 中修改了视频,但在第二个循环中没有修改,它只是检查值。

底线是,您的代码有效,您可能只是调用不正确。

var videos = [{},{},{},{},{},{},{},{},{},{},{}];
var clipLength = 2;

var output1 = '';
let n=videos[0].start;
n = 0;

videos.forEach((element, index) => {
    videos[n].start = n * clipLength;
    output1 += n + ': ' + videos[n].start+'; ';
    n++;
});
console.log(output1);

var output2 = '';
for (var property2 in videos) {
    output2 += property2 + ': ' + videos[property2].start+'; ';
}
console.log(output2);

【讨论】:

  • 这就是它应该工作的方式!但不幸的是,我得到了上述结果。我称其为相同(正确)顺序。
  • 您能否分享您的完整代码或在某处复制它(codepen、jsfiddle,甚至直接 stackoverflow,就像我在回答中所做的那样)?您的错误必须在其他地方,因为它在答案中起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 2021-04-26
相关资源
最近更新 更多