javascript - Create an array and check against it -


i not sure of how this, want create array , able add new items array. since items supposed random number, when new instance created checked against rest of array , sure number has generated not in array. how accomplish this?


i looked @ Šime vidas's answer , seems work, tried shorten

var arr = [];   function add(a) { var n =  ~~(math.random() * 100); (var = 0; < a.length; i++) {     if ( a[i] === n) { a.push(n) } }  }  (var i=0; i<5; i++){     add(arr) }  document.getelementbyid('output').innerhtml += arr; 

and don't understand why wouldn't work. pretty same thing, correct?

var arr = [];   function add(a) {     var n =  ~~(math.random() * 1000);     !is(a, n) && a.push(n); }  function is(a, n) {     (var = 0; < a.length; i++) {         if ( a[i] === n ) { return true; }     }     return false; } 

the add function creates random integer number between 0 , 1000, , adds array.
is function checks whether n number somewhere inside a array.

demo: http://jsfiddle.net/khhmp/2/

demo 2: http://jsfiddle.net/khhmp/3/

(demo 2 shows number added array if it's not in it.)


btw

!is(a, n) && a.push(n); 

is short form of this:

if ( is(a, n) == false ) { a.push(n); } 

the number added array if is(a, n) returns false.


update

var arr = [];   function add(a) {     var n =  ~~(math.random() * 1000),         ok = true;      (var = 0; < a.length; i++) {         if ( a[i] === n ) { ok = false; }     }      ok && a.push(n); } 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -