在Java脚本中将字符串转换为整数,而无需使用任何内置函数

时间:2019-02-28 07:09:45

标签: javascript

在不使用任何函数和方法的情况下,是否有技巧在javascript中将字符串转换为整数?

var s = "5"
console.log(typeof(s)) // out put is string 
console.log(typeof(parseInt(s))) // i want out put which is number with out using parseInt() or other functions for optimizing code.

任何帮助将不胜感激。预先感谢。

3 个答案:

答案 0 :(得分:4)

您可以使用一元加(+)将字符串转换为数字。除了一些代码优化之外,这无济于事。

var s = "5"
s = +s;
console.log(typeof(s), s);

var s = "5.5"
s = +s;
console.log(typeof(s), s);

答案 1 :(得分:3)

这是在没有任何内置函数的情况下将字符串转换为int的最有效方法,请参见下面的代码

var s = "5"
var i = s - 0
console.log(typeof(i)) // you will get a number with out using any built in function... because (-) cast string in to integer with a number

答案 2 :(得分:3)

您可以尝试使用按位运算符#cloud-config package_update: true # Setup swap memory disk_setup: ephemeral0: table_type: mbr layout: [66, [33, 82]] overwrite: True fs_setup: - device: ephemeral0.1 filesystem: ext4 - device: ephemeral0.2 filesystem: swap mounts: - ["ephemeral0.1", "/mnt"] - ["ephemeral0.2", "none", "swap", "sw", "0", "0"] # Enable Docker's swap limit support bootcmd: - [ sh, -c, 'sudo echo GRUB_CMDLINE_LINUX=\"cgroup_enable=memory swapaccount=1\" >> /etc/default/grub' ] - [ sh, -c, 'sudo update-grub' ] # Install docker and docker-compose runcmd: - [ sh, -c, 'curl -sSL https://get.docker.com/ | sh' ] - [ sh, -c, 'sudo curl -L https://github.com/docker/compose/releases/download/$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep "tag_name" | cut -d \" -f4)/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose' ] - [ sh, -c, 'sudo chmod +x /usr/local/bin/docker-compose' ] # Add default auto created user to docker group system_info: default_user: groups: [docker] 。这会将值转换为整数。但是,这也会将浮点值转换为整数。

s|0