Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/425.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回ObjectObject的JavaScript,没有按预期返回的字段{a:2,b:2,c:1}_Javascript - Fatal编程技术网

返回ObjectObject的JavaScript,没有按预期返回的字段{a:2,b:2,c:1}

返回ObjectObject的JavaScript,没有按预期返回的字段{a:2,b:2,c:1},javascript,Javascript,我正在构造一个reduce函数,它接受一个数组、一个回调和一个初始值,并返回一个值。该函数满足以下条件的2/3:不应改变输入数组,应汇总数组,并应从数组创建“totals”对象 function reduce(array, callback, num) { let sum = 0; let totals; for ( let i = 0; i < array.length; i++) { sum += num + array[i]; } return sum

我正在构造一个reduce函数,它接受一个数组、一个回调和一个初始值,并返回一个值。该函数满足以下条件的2/3:不应改变输入数组,应汇总数组,并应从数组创建“totals”对象

function reduce(array, callback, num) {
  let sum = 0;
  let totals;
  for ( let i = 0; i < array.length; i++) {
    sum += num + array[i];
  }
  return sum
   array.forEach(function(ele, index){
    totals = callback(totals, ele);
  });
  return totals;
}

欢迎在此输入。

首先,
return
关键字结束函数。因此,写任何超过返回值的代码都不会有任何效果。事实上,您不需要返回,也不需要上面的循环:

函数reduce(数组、回调、总计){
//默认情况下,如果totals为空,reduce将使用第一个元素作为基数
如果(总计类型==“未定义”&&array.length>0){
总计=数组[0];
array=array.slice(1);
}
forEach(函数(ele,index){
总计=回调(总计,ele);
});
返回总数;
}
log(reduce([1,2,3],(sum,v)=>sum+v));//6.

log(reduce([1,2,3],(sum,v)=>sum+v,3));//9
对不起,您的代码毫无意义。原因如下:

function reduce(array, callback, num) {
  let sum = 0;
  let totals;

  // Problem one - you are hardcoding behaviour instead of 
  // using a callback which is normally supposed to inject the reducing logics
  for ( let i = 0; i < array.length; i++) {
    sum += num + array[i];
  }
  return sum // after that line all the code is a deadcode
  // as the return command terminates your reduce function 
  // and returns sum
   array.forEach(function(ele, index){
    totals = callback(totals, ele);
  // as I said this is the dead code. Anyways pay attention that
  // totals variable is instantiated but undefined. What are you planning 
  // to achieve by providing it to the callback function?
  });
  return totals;
}
函数reduce(数组、回调、num){
设和=0;
让总数;
//问题一-您正在硬编码行为,而不是
//使用通常被认为是注入还原逻辑的回调
for(设i=0;i
下面是我对标准JS API Array.prototype.reduce函数的实现:

function myReduce (cb, initialValue) {
 if (!Array.isArray(this) || (!this.length && !initialValue))
   throw TypeError;

 // making a copy of the original array to prevent
 // it from being mutated by a callback
 const array = [...this];

 // if no initial value is provided, we take the first element
 // of array instead
 let acc = initialValue || array[0];

 // if no initialValue is provided we start iteration from 1
 // else the iterations starts from 0
 for (let i = Number(!initialValue); i < array.length; i++)
    acc = cb (acc, array[i], i, array);

 return acc;
}

// here's what you supposedly are trying to achieve:
const myArray = [1,2,3,4,5];

// hereinafter I will use Function.prototype.call 
// to bind the array to myReduce function
console.log(myReduce.call(myArray, (acc, cur) => acc + cur)); // => 15

// And more advanced example of a simple array-to-object mapper:
const myArray2 = [
  {id: 0, email: 'user0@co.cc'},
  {id: 1, email: 'user1@co.cc'},
  {id: 2, email: 'user2@co.cc'},
];

console.log(myReduce.call(
  myArray2, // this
  (acc, {email, id}) => ({...acc, [id]:  email}), // cb
  {} // initial state
)); // => Object {0: "user0@co.cc", 1: "user1@co.cc", 2: "user2@co.cc"}
函数myReduce(cb,初始值){
if(!Array.isArray(this)| |(!this.length&&!initialValue))
抛出类型错误;
//制作原始阵列的副本以防止
//它不会被回调变异
常量数组=[…此];
//如果没有提供初始值,则取第一个元素
//而不是数组
设acc=initialValue | |数组[0];
//若并没有提供初始值,我们从1开始迭代
//否则迭代从0开始
for(设i=Number(!initialValue);iacc+cur));//=>15
//更高级的简单数组到对象映射器示例:
常量myArray2=[
{id:0,电子邮件:'user0@co.cc'},
{id:1,电子邮件:'user1@co.cc'},
{id:2,电子邮件:'user2@co.cc'},
];
console.log(myReduce.call(
myArray2,//这个
(acc,{email,id})=>({…acc,[id]:email}),//cb
{}//初始状态
)); // => 对象{0:“user0@co.cc", 1: "user1@co.cc", 2: "user2@co.cc"}

希望这会有帮助。祝你好运

提示:
return
关键字结束函数。在
返回和
之后写入代码是有用的。函数不应该有多个
无条件返回
。由于首先执行
sum
的返回,因此此函数永远不会获得任何
totals
值。然后,下一个问题是在删除该函数后覆盖
totals
循环的每次迭代return@charlietfl为什么这会成为一个问题?这就是
reduce
的工作原理。回调函数返回一个值,该值将传递给回调函数的下一个调用,然后依次传递给SWR(爬行、站立、行走、运行)。没有捷径了,谢谢你。快速提问,为什么array.slice从第一个元素1开始而不是从0开始?@Codestudio
array.slice(1)
实际上从原始数组创建了一个新数组,但是从index
1
开始,因为我们想删除第一个数组(我们已经通过执行
totals=array[0]
来获取它)如果不提供
totals
参数,则
reduce
的默认行为是使用第一个元素作为起始值,它将只调用数组其余部分(而不是第一个)的回调
function myReduce (cb, initialValue) {
 if (!Array.isArray(this) || (!this.length && !initialValue))
   throw TypeError;

 // making a copy of the original array to prevent
 // it from being mutated by a callback
 const array = [...this];

 // if no initial value is provided, we take the first element
 // of array instead
 let acc = initialValue || array[0];

 // if no initialValue is provided we start iteration from 1
 // else the iterations starts from 0
 for (let i = Number(!initialValue); i < array.length; i++)
    acc = cb (acc, array[i], i, array);

 return acc;
}

// here's what you supposedly are trying to achieve:
const myArray = [1,2,3,4,5];

// hereinafter I will use Function.prototype.call 
// to bind the array to myReduce function
console.log(myReduce.call(myArray, (acc, cur) => acc + cur)); // => 15

// And more advanced example of a simple array-to-object mapper:
const myArray2 = [
  {id: 0, email: 'user0@co.cc'},
  {id: 1, email: 'user1@co.cc'},
  {id: 2, email: 'user2@co.cc'},
];

console.log(myReduce.call(
  myArray2, // this
  (acc, {email, id}) => ({...acc, [id]:  email}), // cb
  {} // initial state
)); // => Object {0: "user0@co.cc", 1: "user1@co.cc", 2: "user2@co.cc"}