1
votes

Comment imiter l'argument step de Python en JavaScript?

En Python, je peux écraser des éléments dans un tableau en utilisant la syntaxe de découpage et en passant un argument d'étape. Par exemple:

alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
alist[::2] = ["foo", "foo", "foo", "foo", "foo"]
print(alist) # ['foo', 2, 'foo', 4, 'foo', 6, 'foo', 8, 'foo', 10]

Existe-t-il un moyen d'imiter ce comportement en JavaScript?


0 commentaires

3 Réponses :


3
votes

Vous pouvez implémenter une telle fonction vous-même avec une boucle for .

var alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var alist2 = ["foo", "foo", "foo", "foo", "foo"]
function overwrite(arr, arr2, step){
  for(let i = 0, j = 0; i < arr.length && j < arr2.length; i += step, j++){
    arr[i] = arr2[j];
  }
}
overwrite(alist, alist2, 2);
console.log(alist);


0 commentaires

2
votes

Vous pouvez utiliser map et renvoyer un élément de la deuxième liste à chaque itération paire.

const alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const blist = ["foo", "foo", "foo", "foo", "foo"];
const clist = alist.map((e,i) => i%2==0?blist[i/2]:e);

console.log (clist)


0 commentaires

1
votes

Faites-moi savoir si cela fonctionne pour vous:

function range(from, to){
  let f = from, t = to;
  if(t === undefined){
    t = from; f = 0;
  }
  for(var i=f,r=[]; i<=t; i++){
    r.push(i);
  }
  return r;
}
function step(a, num, b){
  const r = b.slice();
  for(let i=num-1,l=a.length; i<l; i+=num){
    if(!a.hasOwnProperty(i)){
      break;
    }
    r.splice(i, 0, a[i]);
  }
  return r;
}
const aList = range(1, 10), bList = ['foo', 'bar', 'foo', 'bar', 'foo', 'bar'];
console.log(step(aList, 2, bList)); console.log(step(aList, 3, bList));


0 commentaires