jquery - Where is the flaw in my implementing a firstOrDefault function in Javascript? -


i'm trying practice javascript chops , trying figure out flaw in attempted implementation of firstordefault function exists in c#.

html:

<div id="#resultdiv"></div> 

js:

function firstordefault ( arr, f )  {     var result = null;     ( var = 0, n = arr.length; < n; ++i )         if (f(i)) return i;              return result; }  $(document).ready(function(){     var myarray = [1, 5, 9, 18];     var myfunction = function ( x ) { return x > 5; };     $('#resultdiv').text(firstordefault(myarray, myfunction)); // should print 9 inside #resultdiv }); 

fiddle: http://jsfiddle.net/z3h06mwo/

also, should instead extending array? if so, how do that?

you're passing index (0, 1, 2, ...) f, not value; you're returning index, not value, said wanted return 9 value.

function firstordefault ( arr, f )  {     var result = null;     var value;                                      // <===     ( var = 0, n = arr.length; < n; ++i ) {         value = arr[i];                             // <===         if (f(value)) return value;         //    ^^^^^          ^^^^^     }     return result; } 

live example:

function firstordefault(arr, f) {    var result = null;    var value;    (var = 0, n = arr.length; < n; ++i) {      value = arr[i];      if (f(value)) return value;    }    return result;  }    var myarray = [1, 5, 9, 18];  var myfunction = function(x) {    return x > 5;  };  $('#resultdiv').text(firstordefault(myarray, myfunction)); // should print 9 inside #resultdiv
<div id="resultdiv"></div>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


side note: see how had add braces there because i'd added second statement? fwiw, recommend always using braces. ide can help.


Comments