js异步获取一个数组在循环通过异步函数将数组中的每个数据添加一个新属性返回整个数组不使用async
/ / 定义一个异步函数,用于将每个元素添加一个新属性 function addProp (arr, callback) { var count = 0; arr.forEach (function (item, index) { setTimeout (function () { item.newProp = 'new property'; count ++; if (count === arr.length) { callback (arr); } }, 0); }); }
// 异步获取数组 var arr = [1, 2, 3, 4, 5]; setTimeout (function () { // 调用异步函数 addProp (arr, function (newArr) { console.log (newArr);// 输出带有新属性的整个数组 }); }, 0);
原文地址: https://www.cveoy.top/t/topic/gZah 著作权归作者所有。请勿转载和采集!