Question 1: Given an array (such as [2, 7, 11, 15]), find the sum of the values of any two array elements (cannot be the same array element) to a specified value (such as 9 ) array subscript.
For example, given [2, 7, 11, 15], target = 9, find the subscript of the array element that meets the conditions return [0,1]
function findIndex(arr, target) {
var result = [];
for(var i = 0; i < arr.length; i++) {
for(var j = i + 1; j < arr.length; j++) {
if(arr[i] + arr[j] === target) {
result.push([i, j]);
}
}
}
return result;
}
console.log(findIndex([2, 7, 11, 15], 9)); // [0, 1]
Problem 2: Encapsulation function result 10 obtained final output 10=10987< /span>2* 1=36288003456
//1.第一种方法
function factorial(n) {
var result = 1;
for(var i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log("10 的阶乘为:" + factorial(10));
console.log("10 的阶乘展开为:" + "10=" + factorial(10).toString().replace(/(\d)\*(\d)/g, "$1*$2"));
//2.第二种方法
function fc(){
var str='10=',sum=1;
for(var i=10;i>=1;i--){
sum*=i;
if(i==1){
str+=i+'='
}else{
str+=i+'*'
}
}
console.log(str+sum);
}
fc();
Question 3: Given a string, output the length of the longest word (like an array, you can use a for loop to traverse, or you can get the length through the length attribute)
function longestWord(str) {
var words = str.split(' ');
var longest = 0;
for(var i = 0; i < words.length; i++) {
if(words[i].length > longest) {
longest = words[i].length;
}
}
return longest;
}
console.log(longestWord("i love World")); // 5
Question 4: The number of narcissus within 100 to 1000. Units cube + tens cube + hundreds cube = number of narcissus
function narcissisticNumbers(num) {
var result = [];
for(var i = 100; i <= num; i++) {
var str = i.toString();
var len = str.length;
var sum = 0;
for(var j = 0; j < len; j++) {
sum += parseInt(str[j], 10) ** len;
}
if(i === sum) {
result.push(i);
}
}
return result;
}
console.log(narcissisticNumbers(1000)); // [153, 370, 371, 407]