修改for循环
虽然下面的代码很好地使用for循环遍历数组,然后将基于数组值的列名打印到Excel表中,但我想知道是否可以修改代码,将数组中包含单词“苹果”的数组进行分组,并像下面提供的示例一样创build一个excel列名称“苹果”。
我不确定如何修改for循环来完成此操作。
预期的结果是:
function search_array(arr, str){ var searchExp = new RegExp(str,"gi"); return (searchExp.test(arr))?true:false; } var temp = ["red apples", "fuji apples", "grannysmith apples", "mcintosh apples", "honeycrisp apples", "gala apples", "oranges", "pears", "bananas"] var col = 2 for(var i = 0; i < temp.length; i++){ if (search_array(temp[i], "apples") == true) { Sheet.Cells(2,col).Value = "apples" } else { Sheet.Cells(2,col).Value = temp[i] } ++col }
在循环中向你的代码添加一个标志:
var col = 2, foundApples = false, hasApplesInString; for(var i = 0; i < temp.length; i++){ hasApplesInString = search_array(temp[i], "apples"); if ( !hasApplesInString || !foundApples ) { Sheet.Cells(2,col).Value = temp[i]; if (hasApplesInString) { foundApples = true }; col++; } }
你可以先过滤数组,添加你正在寻找的单词,然后迭代
var temp = ["red apples", "fuji apples", "grannysmith apples", "mcintosh apples", "honeycrisp apples", "gala apples", "oranges", "pears", "bananas"] var col = 2; var word = 'apples'; var has = false; temp = temp.filter(function(item) { var i = item.indexOf(word) === -1; if (i) has = true; return i; }); if (has) temp.unshift(word); for(var i = 0; i < temp.length; i++){ Sheet.Cells(2,col).Value = temp[i] }
小提琴
您可以为已过滤的值创build一个新数组,并将这些新值推入列:
var temp = ["red apples", "fuji apples", "grannysmith apples", "mcintosh apples", "honeycrisp apples", "gala apples", "oranges", "pears", "bananas"] var temp_filtered = []; for (var i = 0; i < temp.length; i++) { var value = temp[i] if (search_array(temp[i], "apples") == true) { value = "apples" } if (temp_filtered.indexOf(value) === -1) { temp_filtered.push(value); } } var col = 2; for (var j = 0; j < temp_filtered.lenth; j++) { Sheet.Cells(2, col).Value = temp_filtered[j]; ++col; }
如果水果永远是“名字空间水果”(富士苹果)。
这是我将如何做到这一点。
var fruitList = ["red apples", "fuji apples", "grannysmith apples", "mcintosh apples", "honeycrisp apples", "gala apples", "oranges", "pears", "bananas"] console.log(uniqueFruit(fruitList)); function uniqueFruit(arr) { var returnarray = []; for (var i = 0; i < arr.length - 1; i++) {//iterate through the fruitList var fruit = arr[i].split(' ').reverse();//split each into an array of two words // ["red","apples"] // Reverse the order // ["apples","red"] fruit = fruit[0]; // fruit = "apples" if (returnarray.indexOf(fruit) < 0) { // find apples in returnarray returnarray.push(fruit); // if not there push it into it } } return returnarray; }