简体   繁体   English

如何在NodeJS中反转数字/字符串?

[英]How to reverse a number/string in NodeJS?

I have used this code to reverse a number but it is not working. 我已经使用此代码来反转数字,但是它不起作用。

var buffer = new Buffer("<inputNumber>", "ucs2");
Array.prototype.reverse.call(new Unit16Array(buffer));
return buffer.toString("ucs2");

Where was I wrong? 我哪里错了? Is this approach right? 这种方法正确吗? Any other way of reversing a number/string without using buffer? 还有其他不使用缓冲区来反转数字/字符串的方法吗?

There are different ways to convert number to string : 有多种方法将数字转换为字符串:

String literal -> str = "" + num + "";
String constructor -> str = String(num);
toString -> str = num.toString();
String Literal simple -> str = "" + num;

The split() method is used to split a String object into an array of strings by separating the string into substrings. split()方法用于通过将字符串分成子字符串来将String对象拆分为字符串数组。

Code : console.log('1000'.split(""));
Output : ["1", "0", "0", "0"]

The reverse() method is used to reverse an array in place. reverse()方法用于在适当位置反转数组。 The first array element becomes the last and the last becomes the first. 第一个数组元素变为最后一个,最后一个数组变为第一个。

Code : console.log(["1", "0", "0", "0"].reverse());
Output : ["0", "0", "0", "1"]

The join() method is used to join all elements of an array into a string. join()方法用于将数组的所有元素连接到字符串中。

Code : console.log(["1", "0", "0", "0"].reverse().join(""));
Output : "0001"

To reverse a number first you have to convert it into string. 首先要反转数字,您必须将其转换为字符串。 Convert that string into array. 将该字符串转换为数组。 Reverse the array and join it to make a string then parse that string to number 反转数组并将其连接以创建字符串,然后将该字符串解析为数字

var num = 1543;
var reverseNum = parseInt(a.toString().split("").reverse().join(""));
//Output : 3451

I hope this will help you. 我希望这能帮到您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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