1

我有一个名为uncompletedSteps()

function uncompletedSteps(completedSteps) {
    // completedSteps is an array
}

此函数应检查并返回所有不等于completedSteps的元素的索引:completedStepstrue

if (completedSteps[i] === true) {
    // add to return list
}

换句话说,如果有:

var completedSteps = [
    true,
    null,
    true
];

然后uncompletedSteps()应该返回[0, 2]

这应该是什么uncompletedSteps()样子?(ECMAScript5 好的。)

4

4 回答 4

4

使用reduce

function uncompletedSteps(steps){
   return steps.reduce(function(memo, entry, i) { 
      return memo.concat(entry ? i : []);
   }, [])
}

使用forEach

function uncompletedSteps(steps){
   var uncompleted = [];
   steps.forEach(function(entry,i) { 
      if(entry) uncompleted.push(i); 
   })
   return uncompleted;
}

使用mapfilter

function uncompletedSteps(steps){
   return steps.map(function(entry, i) {
      return entry ? i : null;
   }).filter(function(entry) {
      return entry != null;
   });
}
于 2011-03-16T21:35:44.420 回答
1
var count = [];
for ( var i = 0; i<completedSteps.length; i++ ) {
  if(completedSteps[i]) {
    count.push(i);
  }
}
return count;
于 2011-03-16T21:32:28.227 回答
0
var arr = [true, true, null, true];
arr.map(function(el, i) { 
    return el ? i : -1; 
}).filter(function(el) {
    return el != -1;
})

回报:

 [0, 1, 3]
于 2011-03-16T21:48:18.963 回答
0

此函数应检查 completedSteps 并返回所有不等于 true 的 completedSteps 元素的索引:

使用以下过程来实现向后兼容性:

  • 多次替换以插入转换为空字符串null的值的字符串
  • 一个replace要删除true
  • 另一个replace带有替换回调以插入索引
  • 另一个replace删除前导逗号
  • 另一个replace删除成对的逗号

例如:

function foo(match, offset, fullstring)
  {
  foo.i = foo.i + 1 || 0;
  if (match === "true") 
    {
    return "";
    }
  else
    {
    return foo.i;
    }
  }

function uncompletedSteps(node)
  {
  return String(node).replace(/^,/ , "null,").replace(/,$/ , ",null").replace(/,,/g , ",null,").replace(/[^,]+/g, foo).replace(/^,/,"").replace(/,,/g,",")
  }

var completedSteps = [
    null,
    true,
    false,
    true,
    null,
    false,
    true,
    null
];

uncompletedSteps(completedSteps); // "0,2,4,5,7"
于 2014-01-30T20:44:38.447 回答