简体   繁体   中英

using arrow function on Jquery function

having a difficult time converting a Jquery map function to an arrow function.

here is the fiddle .

 // find elements $('button').click(function(e) { let answerArray = $(`[name="foo"]`).map(function() { return $(this).val(); }).get(); console.log(answerArray) let answerArray2 = $(`[name="foo"]`).map(x => $(x).val()).get(); console.log(answerArray2) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="foo"> <input name="foo"> <button> enter </button> 

but I am receiving.

VM118 jquery.js:7977 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined at jQuery.fn.init.val (VM102 jquery.js:7977) at HTMLInputElement.$.map.x ((index):74) at VM102 jquery.js:194 at Function.map (VM102 jquery.js:443) at jQuery.fn.init.map (VM102 jquery.js:193) at HTMLButtonElement. ((index):74) at HTMLButtonElement.dispatch (VM102 jquery.js:5183) at HTMLButtonElement.elemData.handle (VM102 jquery.js:4991)

As per your code x refers to index not element thus you are getting the error.

Use correct callback function arguments of .map() .

Type: Function( Integer index , Element domElement ) => Object A function object that will be invoked for each element in the current set.

 // find elements $('button').click(function(e) { let answerArray2 = $(`[name="foo"]`).map((i, x) => $(x).val()).get(); console.log(answerArray2) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="foo"> <input name="foo"> <button> enter </button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM