简体   繁体   中英

How to use array.push correctly?

var send_value = [current_site_id, current_site_name, current_site_description];
console.log(send_value);
send_value = jQuery(this).is(':checked') ? send_value.push('add') : send_value.push('delete');
console.log(send_value);

The result is

["12", "qwrqweqwer", "qwreqwr"]
4

Where i'm wrong?

PS. Sorry, my mistake was in send_value = , can not understand how it got there

This line send_value = jQuery(this).is(':checked') ? send_value.push('add') : send_value.push('delete'); send_value = jQuery(this).is(':checked') ? send_value.push('add') : send_value.push('delete'); assigns the return value of push to send_value , it doesn't push anything. The return value is the new length of the array object, as you can see in the specifications

Try this:

send_value.push(jQuery(this).is(':checked') ? 'add' : 'delete');

Push the resulting value of your ternary
If you find it more readable, you could turn your ternary into an expression, rather then a statement:

(jQuery(this).is(':checked') ? send_value.push('add') : send_value.push('delete'));//<-- notice surrounding parentheses

But, frankly, if your concerned about readability, it's best to do away with ternaries all together IMHO.

push returns the length of the array after the pushes are done. Try this:

var send_value = [current_site_id, current_site_name, current_site_description];
console.log(send_value);
send_value.push( jQuery(this).is(':checked') ? 'add' : 'delete' );
console.log(send_value);

Additionally you should use an object not an array. send_value.site_id reads better than send_value[0] ...

var result = jQuery(this).is(':checked') ? 'add' : 'delete';
    send_value.push(result);

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