Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #20288

Re: Javascript shift()

From Stefan Weiss <krewecherl@gmail.com>
Newsgroups comp.lang.javascript
Subject Re: Javascript shift()
Date 2013-06-14 15:03 +0200
Organization albasani.net
Message-ID <kpf4bg$cid$1@news.albasani.net> (permalink)
References <aa28fb0d-9a33-4649-a561-88127227e14b@y5g2000vbg.googlegroups.com>

Show all headers | View raw


On 2013-06-14 09:15, JT wrote:
> Can i somehow tell which javascript elements to shift?
> Is something like following possible
> element[i].shift()
> 
> Many times one want to change items not necessarily at element[0], and
> sometimes you want to swap them with another index.
> 
> I think the shift function should take one or two parameters or a new
> function should be constructed.

You're probably looking for the splice() method. To insert an element at
index 2:

  var a = [2, 3, 5, 6];
  a.splice(2, 0, 4);
  // a is now [2, 3, 4, 5, 6]

shift()/unshift() and push()/pop() always work on the ends of an array;
you could think of them as specialized cases of splice().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

> element [x][y].swap();
> 
> It is not hard to swap elements but it make more sense then the
> noneflexible shift() function.

Why would you need shift() for element swapping? Something like this
should be sufficient (untested):

  Array.prototype.swap = function (a, b) {
      var tmp = this[a];
      this[a] = this[b];
      this[b] = tmp;
  };

  var a = [2, 3, 5, 4, 6];
  a.swap(2, 3);
  // a is now [2, 3, 4, 5, 6];

(BTW: better use Object.defineProperty - where supported - instead of
directly augmenting a native prototype.)


- stefan

Back to comp.lang.javascript | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

Javascript shift() JT <jonas.thornvall@gmail.com> - 2013-06-14 00:15 -0700
  Re: Javascript shift() Denis McMahon <denismfmcmahon@gmail.com> - 2013-06-14 11:29 +0000
    Re: Javascript shift() Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2013-06-14 15:01 +0200
  Re: Javascript shift() Stefan Weiss <krewecherl@gmail.com> - 2013-06-14 15:03 +0200

csiph-web