javascript - alternative to for loop -


this question has answer here:

how use .foreach instead of loop?

'use strict';  var score = (function(){         function updatescore() {             for(var = 0; < arguments.length; i++) {                 this.score += arguments[i];             }// want use .foreach here instead of loop.             return this.score;         }          return {             update: updatescore         } })();  var soccer = {     name: 'soccer',     score: 0 }  score.update.apply(soccer, [1,2,3])  console.log(soccer.score) 

this log 6.

i tried

function updatescore() {   arguments.foreach((args, i) => {     this.score += args[i];   };   return this.score; };  

error log: arguments.foreach not function

in modern (es2015) javascript can use array.from():

array.from(arguments).foreach((arg) => {   this.score += arg; }); 

you don't need use array indexing, .foreach() function passes each array element callback function first argument. (it pass index second argument, in case wouldn't need use that.)

it's important note if arguments object passed out of function (as here), overall function may considered ineligible optimization. that's because arguments object has weird properties make hard optimizer know what's going on , whether it's safe make assumptions how local variables change. if that's concern, option copy arguments simple array for loop.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -