Mp *_*ega 5 javascript arrays logic
我正在尝试创建一个可以操作数组的函数...
var myArray = [2, 1, 1, 1, 1];
Run Code Online (Sandbox Code Playgroud)
现在我希望它像这样
[3,1,1,1]
现在我的函数接受3个参数
我的目标是接受indexTarget,例如
myFunction(myArray,0,3); //myArray is [2, 1, 1, 1, 1]
Run Code Online (Sandbox Code Playgroud)
你可以看到我想我的功能在循环遍历myArray所以它会尝试在阵列中添加数字,直到它达到了morphToValue所以就成了[3,1,1,1],它会清除2第一指标和1对获得第二个指数3.如果它对morphToValue上的超出添加太多,它也将减去数组上的任何数字
另一个例子就是这样我想要的数组
var myArray = [2,1,1,1,1];
就像这样
[2, 1, 3];
Run Code Online (Sandbox Code Playgroud)
通过像这样调用myFunction
myFunction(myArray,2,3);
Run Code Online (Sandbox Code Playgroud)
我该怎样才能做到这一点?如果我要在数组的最后一个索引中设置indexTarget,我还想继续迭代数组的开头,这样就像这样
var myArray = [2,1,1,1,1];
它会成为
[1, 1, 1, 3]; //when I invoke myFunction(myArray,4,3);
Run Code Online (Sandbox Code Playgroud)
如果你不明白的话请发表评论....
这是我到目前为止所尝试的http://jsfiddle.net/eESNj/
var myArray = ['2', '1', '1', '1', '1'];
indexPurge(myArray, 0, 3);
function indexPurge(haystack, indexTarget, morphToValue) {
var toIntHaystack = [];
for (var i = 0; i < haystack.length; i++) {
toIntHaystack.push(parseInt(haystack[i]));
}
console.log(toIntHaystack); //before
var i = 0;
var purgedValue = 0;
do {
console.log(i + ' - ' + toIntHaystack[i]);
purgedValue += toIntHaystack[i];
toIntHaystack.splice(i, 1);
if (purgedValue >= morphToValue) {
break;
}
i++;
} while (i < toIntHaystack.length);
toIntHaystack.splice(indexTarget, 0, morphToValue); //after
console.log(toIntHaystack);
}
Run Code Online (Sandbox Code Playgroud)
我解决了我自己的问题..我希望这能帮助有同样问题的人
var myarrayx = [1,1,3]; //5
function morphArray(myarray, index, target){
//accumulate value on the array to gain target value
var accu = 0;
for(var i = 0; i < myarray.length; i++){
var thisIndex = myarray[i];
for(var j = 0; j < thisIndex; j++){
if(accu != target){
myarray[i]--;
accu++;
}
else{
break;
}
}
}
//remove the zeroes on the array
for(var k = 0; k < myarray.length; k++){
if(myarray[k] == 0){
myarray.splice(k, 1);
}
}
//check if the target index is still available
if((myarray.length - 1) > index){
//index is not available anymore.. just push it
myarray.push(target);
}
else{
//insert the element in the desired index
myarray.splice(index, 0, target);
}
return myarray;
}
console.log('----'+morphArray(myarrayx, 0, 2));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
522 次 |
| 最近记录: |