xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js swap array

js swap array

ES6 swap array

就地交换

  1. no need let , const

[
  b,
  a,
] = [
  a,
  b,
];

// ES6 swap
const arr = [1, 2];

[
  arr[0],
  arr[1],
] = [
  arr[1],
  arr[0],
];

arr;
// (2) [2, 1]

ES5

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
  let len = Math.floor(s.length / 2);
  for(let i = 0; i < len; i++) {
    // ES5 swap
    const temp = s[i];
    s[i] = s[s.length - i - 1];
    s[s.length - i - 1] = temp;
  }
};

ES6


/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
  let len = Math.floor(s.length / 2);
  for(let i = 0; i <= len; i++) {
    // ES6 swap, more faster 🚀
    [
      s[s.length - i - 1],
      s[i],
    ] = [
      s[i],
      s[s.length - i - 1],
    ];
  }
};

leetcode

https://leetcode.com/problems/reverse-string/

/**
 * @param {character[]} s
 * @return {void} Do not return anything, modify s in-place instead.
 */
var reverseString = function(s) {
  let len = Math.floor(s.length / 2);
  // if(s.length % 2 === 0) {
  //   len -= 1;
  // }
  // for(let i = 0; i <= len; i++) {
  for(let i = 0; i < len; i++) {
    // ES6 swap, more faster 🚀
    [
      s[s.length - i - 1],
      s[i],
    ] = [
      s[i],
      s[s.length - i - 1],
    ];
    // const temp = s[i];
    // s[i] = s[s.length - i - 1];
    // s[s.length - i - 1] = temp;
  }
  // return Array.from(s).reverse().join(``);
};

https://stackoverflow.com/search?q=js+swap+array

refs

destructuring assignment / 解构赋值

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

const log = console.log;

let a, b, rest;

[a, b] = [10, 20];

log(a);
// 10

log(b);
// 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

log(rest);
// [30,40,50]


refs



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-09-22 10:50  xgqfrms  阅读(732)  评论(4编辑  收藏  举报