Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Can someone help me fix my code?
The function is like the Eval function but has a √ added but it doesn't work
function Eval(n) {
var a = n.split("√").length - 1;
var b = n.split("√").length;
var c = a.replace("√" + d, e);
var d = parseFloat(b[1]);
var e = Math.sqrt(d);
while (a != 0) {
b();
d();
e();
c();
return;
}
}
document.write(Eval("64+√68+32"));
There are some issues with your code and going by your approach, I have updated the code to following. Please see, whether it helps!
Please note, I am assuming as per the name of the function, that you want to evaluate the expression. Also, there are other assumptions as well, like there will be only one square root expression and all operations will be additive.
function Eval(n) {
var b = n.split("√"); // you were expecting b to be an array
var a = b.length - 1; // you can use b here
var d = parseFloat(b[1]); // d should have been assigned before using in c
var e = Math.sqrt(d);
var c = n.replace("√" + d, e);
return c.split("+").reduce(function(a, b) {
return a + parseFloat(b); // sum up all the values
}, 0);
}
console.log(Eval("64+√68+32"));
You can try tweaking here
function eval(n){
var numbers = n.split('+'); // split the exepression with the + operator
var result = 0; // initaliaze the result to 0
for(number of numbers){ // for each number of numbers
if(number.indexOf('√') !== -1){ // if the number contains sqrt
number = +number.substring(1, number.length); // cast to int
result += Math.sqrt(number);
}else{
number = +number; // cast string to int, NaN if not possible
result += number;
}
}
return result;
}
This function will work for you additions.
Not that this is just a point to start, and not the best way of doing it, I tried to be the more comprehensive seeing that you are a beginner in javascript
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i've written
var i = 0;
var x = 0;
var y = 0;
var z = 0;
each variable is incremented by the user, however when i write
function blue() {
console.log(Math.max(i, x, y, z))
}
then I simply get back the highest number, not the name of the highest variable. The goal for this code eventually is to tell the user what number they are, and link them to the corresponding number's information. I've tried converting to an array however I'm a beginner with javascript and unsure where to go from here, would greatly appreciate any advice :)
repository for code in question is: https://github.com/LukeMcHenry311/showingproblem
inside of quiz folder
test.html
test.js
var i = 1;
var x = 3;
var y = 2;
var z = 0;
console.log(Object.entries({i,x,y,z}).sort(([, a], [, b]) => b - a)[0]);
You can use Array.prototype.reduce() with Object.entries():
var i = 1;
var x = 3;
var y = 2;
var z = 0;
max = Object.entries({ i, x, y, z }).reduce(function(carry, [key, value]) {
if (value > carry.value) {
carry.key = key
carry.value = value
}
return carry
}, { 'key': null, 'value': null });
console.log(max); // { key: 'x', value: 3 }
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am a student studying JavaScript.
It hasn't been long since I studied.
Example, createPhoneNumber
The length is up to 11 digits.
I wrote the code in question like this.
function createPhoneNumber(arr) {
let first = '(010)';
if(arr.length === 11){
return `(${arr.slice(0,3).join('')})${arr.slice(3,7).join('')}-${arr.slice(7,11).join('')}`;
}
return `${first}${arr.slice(0,4).join('')}-${arr.slice(4,8).join('')}`;
}
I think it's very messy code.
Is it better to add a new variable to make it shorter and simpler?
This can be done by Regex:
function createPhoneNumber(arr) {
let first = '(010)';
// the submatch (\D)? is intended to get an empty match when the length of arr is not 11
let reg = arr.length == 11 ? /(\d{3})(\d{4})(\d{4})/ : /(\D)?(\d{4})(\d{0,4})(\d{0,})/;
return arr.join('').replace(reg, (match, $1, $2, $3) => ($1 ? "(" + $1 + ")" : first) + $2 + "-" + $3);
}
console.log(createPhoneNumber([0,1,0,1,2,3,4,5,6,7,8]));
console.log(createPhoneNumber([1,2,3,4,5,6]));
console.log(createPhoneNumber([1,2,3,4,5,6,7,8,9,0,0,0,0,0]));
You want it shorter and simpler? This is subjective but I believe the following applies. Also, I wasn't sure if you misused your 11th digit in your function so... I made it work with 10.
function createPhoneNumber(arr) {
const arrL = arr.length;
let arrI = arrL - 4;
arr.splice(arrI, 0, "-");
arr.splice(arrI -= 3, 0, ")");
arr.splice(0, 0, arrL === 10 ? "(" : "(010");
return arr.join("");
}
If it's just a matter of readability, I suggest a few changes:
Export hard coded values to const.
Don't duplicate your code! like the complicated return you had.
It did look messy - do I decided to separate the number to 3 parts - 3 variables, and use 1 return
const PRE_FIRST = '(010)';
const FULL_NUMBER_LENGTH = 11;
function createPhoneNumber(arr) {
let isFullPhone = FULL_NUMBER_LENGTH === arr.length;
let first = isFullPhone ? arr.slice(0, 3).join('') : PRE_FIRST;
let second = (isFullPhone ? arr.slice(3, 7) : arr.slice(0, 4)).join('');
let third = (isFullPhone ? arr.slice(7, 11) : arr.slice(4, 8)).join('');
return `${first}-${second}-${third}`;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Write a JS code which will print Fibonacci series where End value is not greater than 33. (e.g. 0112358)
var n=10;
function fib(n){
var a=[];
a[0]=0;
a[1]=1;
for(i=2;i<n;i++){
a[i]=a[i-1]+a[i-2];
}
return a;
}
console.log(fib(n));
Try the following:
function fib(n){
var a = 0;
var b = 1;
var c = 0;
document.write(a+" "+b);
for(var i = 2; i < n; i++){
c = a + b
if(c > 33)
break;
a = b;
b = c;
document.write(" "+c);
}
}
fib(10);
I get this solution by using array. but what is efficient way to this task.
function fib(n) {
var arr=[];
var a,b,c;
a=0;
b=1;
arr.push(a);
arr.push(b);
while((a+b)<n){
c=a+b;
a=b;
b=c;
arr.push(c);
}
return arr;
}
console.log(fib(33));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
What's wrong with my code? Dreamweaver keeps telling me I have a syntax error!
function myFunction(); {
var a = 5;
var b = 10;
var c = 15;
var d = a + b + c;
alert("The value of d is: " + d);
}
The error tells me that the syntax error with the function myFunction(); line
You added an unnessesary semicolon after myFunction()
function myFunction() ; <== here {
There's only one issue and that is the semicolon used after the function name.
Try this:
function myFunction() {
var a = 5;
var b = 10;
var c = 15;
var d = a+b+c;
alert("The value of d is: " + d);
}
Dreamweaver is correct you have a bad semicolon which terminates the function before you open the function body (immediately after you declare it)
function myFunction(); {
remove it like
function myFunction() {
var a = 5;
var b = 10;
var c = 15;
var d = a + b + c;
alert("The value of d is: " + d);
}
myFunction();
You have a semicolon after the function signature. Should be:
function myFunction() {
var a = 5;
var b = 10;
var c = 15;
var d = a+b+c;
alert("The value of d is: " + d);
}
Also for future reference, run your code through http://jslint.com for more detailed error messages.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
How to convert below String into arrays in javascript
var data = "[
[[1400586475733,-1],
[1400586535736,-1],
[1400586595739,-1],
[1400586655742,-1],
[1400586715745,-1]],
[[1400586475733,0],
[1400586535736,0],
[1400586595739,0],
[1400586655742,0],
[1400586715745,0]]
]";
expected output is
data[0] = [[1400586475733,-1],[1400586535736,-1],[1400586595739,-1],[1400586655742,-1],[1400586715745,-1]]; ==> of type object Array
data[0][0] = 1400586475733 ==> of type number
data[0][1] = -1 ==> of type number
I haven't tried it out thoroughly, but it should work:
var string = "[[[1400586475733,-1],[1400586535736,-1],[1400586595739,-1],[1400586655742,-1],[1400586715745,-1]],[[1400586475733,0],[1400586535736,0],[1400586595739,0],[1400586655742,0],[1400586715745,0]]]";
var dataFromString = string.split(",");
var finalArray = [];
var arrayStartRegEx = new RegExp(/^\[/);
var arrayEndRegEx = new RegExp(/\]$/);
var currentArray = finalArray;
var arrayHistory = [];
for(var i = 0; i < dataFromString.length; i++) {
var currentString = dataFromString[i];
var closingArray = false;
while(arrayStartRegEx.test(currentString) === true) {
// Save previous array
// createArray
// add to big array
// currentArray = createdArray
// remove bracket
var arr = []
arrayHistory.push(currentArray);
currentArray.push(arr);
currentArray = arr;
currentString = currentString.slice(1,currentString.length - 1);
}
while(arrayEndRegEx.test(currentString) === true){
// remove bracket
// add element to array
// close currentArray
// currentArray = big array
currentString = currentString.slice(0,-1);
if(!closingArray) {
var string = currentString.replace(/\]/g, '');
// Use parseFloat if you know it's going to be a float
currentArray.push(parseInt(string));
closingArray = true;
}
currentArray = arrayHistory.pop();
}
if(arrayStartRegEx.test(currentString) === false && arrayEndRegEx.test(currentString) === false) {
// add element to array
currentArray.push(parseInt(currentString))
}
}
console.log(finalArray);