简体   繁体   English

在 Javascript 中将 char 转换为 String

[英]Convert char to String in Javascript

Read it, Before it gets marked as duplicate Sorry!阅读它,在它被标记为重复之前抱歉! I couldn't come up with a better description of the question我想不出更好的问题描述

Anyways, I was making a simple program which reverses the given word (eg 'word' to 'drow').无论如何,我正在制作一个简单的程序来反转给定的单词(例如'word'到'drow')。 I was trying to convert the String into char array first and then printing each character backwards in the console using for loop.我试图先将 String 转换为 char 数组,然后使用 for 循环在控制台中向后打印每个字符。 However, I need to save the value in a String now that I can't seem to figure out.但是,现在我似乎无法弄清楚,我需要将值保存在 String 中。 This is the code here:这是这里的代码:

 var answer = document.getElementById("ta").value;
 var arr = answer.split("");
      for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
           str = arr[i];
           console.log(str); //it works but displays each character individually
           }

I just want all the characters in a String.我只想要一个字符串中的所有字符。 Please help!请帮忙! Brevity in the answer would be appreciated答案的简洁性将不胜感激

If you want to put all the characters in str you can try this way:如果你想把所有的字符都放在 str 中,你可以试试这样:

str= str+arr[i]

or try this way:或尝试这种方式:

var str = "";
arr.forEach(element => {str= str+element});
 console.log(str)

JavaScript unlike other oops, provide an inherited reverse function that reverses array . JavaScript 与其他 oops 不同,它提供了一个继承的反转 function 来反转数组 So one answer to this whould be:所以对此的一个答案是:

let arr = answer.split("") //note this creates an array with each char as element of array
arr = arr.reverse(); //this reverses the array
let string = arr.join(""); //this joins the array into a single string

Another method would be the one you are trying to do, create your own reverse function. You are doing it all right but just missing a step, that is to join the array, you are simply printing each letter of the array and thats the property of console.log that each console.log prints to a new line.另一种方法是你正在尝试做的,创建你自己的反向 function。你做的很好,但只是错过了一个步骤,那就是加入数组,你只是打印数组的每个字母,这就是属性每个 console.log 打印到一个新行的 console.log。 That explains why you are getting it all in new line.这就解释了为什么您要在新行中获取所有内容。

var answer = document.getElementById("ta").value;
 var arr = answer.split("");
var str ="";
      for(i=arr.length-1;i>=0;i--) { //minus 1 because index starts at 0
           str =str +  arr[i];
           }
console.log(str); //it should be outside the loop and print string once it has been formed

PS:I have given as much detail I can on this to get you started but this is a very basic question and doesnt deserve to be here, you should follow some basic concepts of js on mdn or w3schools. PS:我已经提供了尽可能多的细节来帮助您入门,但这是一个非常基本的问题,不应该出现在这里,您应该在 mdn 或 w3schools 上遵循 js 的一些基本概念。 Plus google your problems before turning to stackoverflow.在转向 stackoverflow 之前加上谷歌你的问题。

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

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