这是我的代码段,反转了用户字符串输入。 我正在尝试接受用户输入并撤消已键入的任何内容。我试图将的值存储为新值。然后用一些方法操纵该变量。
function reverse_it() {
var to_reverse = document.getElementById('to-reverse').value;
var inputValue = to_reverse;
inputValue.split('').reverse().join('');
var reversed = inputValue;
var output_field = document.getElementById('reversed');
output_field.innerHTML = reversed;
};
<h2>Three-Layer Handlers Exercises</h2>
<hr>
<script src="./handler-reverse.js"></script>
to reverse: <input id='to-reverse' value=''></input> <br>
<button onclick='reverse_it()'>reverse it</button> <br>
<p id='reversed'></p><br>
<hr>
<script src="./handler-sort.js"></script>
to sort: <input id='to-sort' value=''></input> <br>
<button onclick='sort_it()'>sort it</button> <br>
<p id='sorted'></p><br>
<hr>
<script src="./handlers-calculator.js"></script>
first number: <input id='first-number' value=''></input><br>
second number: <input id='second-number' value=''></input> <br>
<button onclick='add()'>+</button>
<button onclick='subtract()'>-</button>
<button onclick='multiply()'>*</button>
<button onclick='divide()'>/</button> <br>
<p id='result'></p>
<br><br>
<hr>
<hr>
<a href="http://janke-learning.org" target="_blank"><img src="https://user-images.githubusercontent.com/18554853/50098409-22575780-021c-11e9-99e1-962787adaded.png" width="40" height="40"></img> Janke Learning</a>
我需要接受用户输入并反转。我该怎么做。到目前为止,我尝试了以下代码,但是出了点问题:
function reverse_it() {
// read and process user input
var to_reverse = document.getElementById('to-reverse').value;
// pass user input through core logic
/* write a script to reverse a string */
to_reverse.split('').reverse().join('');
/* assign the result to a variable named 'reversed' */
var reversed = to_reverse; // place-holder, delete this and start over
// report result to user
var output_field = document.getElementById('reversed');
output_field.innerHTML = reversed;
};
答案 0 :(得分:3)
字符串是不可变的。 to_reverse.split('').reverse().join('');
将不会修改原始字符串。您需要将结果存储在变量中。
不仅所有Primitive Types的字符串都无法修改。数组是可以修改的对象,但是某些方法Mutator Methods将更改原始数组。这里的split()
和join()
也不会对原始数组进行突变。
function reverse_it() {
var to_reverse = document.getElementById('to-reverse').value;
var reversed = to_reverse.split('').reverse().join('');
var output_field = document.getElementById('reversed');
output_field.innerHTML = reversed;
};
答案 1 :(得分:1)
您需要将连接的字符串分配给变量,或将其直接传递给变量reversed
。
function reverse_it() {
var to_reverse = document.getElementById('to-reverse').value;
var reversed = to_reverse.split('').reverse().join('');
var output_field = document.getElementById('reversed');
output_field.innerHTML = reversed;
};
答案 2 :(得分:-1)
尝试一下
const reverse_it = () => {
const to_reverse = document.querySelector('#to-reverse');
to_reverse.value.split('').reverse().join('');
const output_field = document.querySelector('#reversed');
output_field.innerHTML = to_reverse;};