assign key correctly to value in javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to map a user defined key to the associated value and it is currently returning undefined for the final (var final). The goal is to collect a user provided input (key) and map it to the associated string from the key:value object and then load a URL using this value. The web page loads incorrectly in the end because the value is undefined. Here is the code:
document.getElementById("btn").onclick = function onLoad() {
var converts = {
'apples' : 'green',
'sky' : 'blue'
};
var myTextField = document.getElementById("myTextarea");
var itemName = myTextField.value;
var final = converts[itemName];
if (document.getElementById('rad1').checked) {
window.open("somewebsite" + final + "restofURL", "this is a new window");
}
}

The problem is that the textarea has a lot of white-spaces in it by default. If the user adds a space, that could cause problems so we need to trim the string:
convert[ itemName.trim() ];
This will remove all the bordering whitespace.

Related

String's split method shows undefined [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to get all characters starting from = inside url:
let url = this.$route.query.item
console.log(typeof(url)) // outputs string
let status = url => url.split('=')[1]
it shows split as undefined. What is the problem and how can be it fixed?
Here is what you want:
let url = "foo=bar";
console.log(typeof (url)) // outputs string
let status = url => url.split('=')[1]
console.log(status(url));// "bar"
I think your this.$route.query.item does not contain = character. if you are looking for current url try this may be
let url = this.$router.currentRoute;
console.log(url); // check if this is the url you expect
let status = 'url does not contain = char';
if(url.includes('='){
status = url.split('=')[1];
}
console.log(status);
note: if you actually need to split this.$route.query.item, console log it and check if it contains = or perhaps add a check for it.

Set get of Object.defineProperty does not work properly undefined is printed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Is it possible to manage object's properties via set get in defineProperty?
I'm not sure that I'm using this sentence properly.
<div id="app"></div>
why
<script>
var div = document.querySelector('#app');
var viewModel = {};
Object.defineProperty(viewModel, 'str' , {
get: function() {
return console.log("access");
},
set: function() {
return console.log("setting");
}
})
</script>
I assume that you have run viewModel.go in console - you will get "access" printed in console, but later you will get undefined as it is a result of this get function:
function() {
console.log("access");
}
This function doesn't have a return clause, so value of go will be undefined.

How can you count the number of occurrences of all of the words in a text area using Javascript? [closed]

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 8 years ago.
Improve this question
If I had a textarea and a user pasted a paragraph into the textarea, can statistics be run on the input using JavaScript on the client side? I was thinking of using an associative array or hash map so array[word] -> # of occurrences, and iterate through word by word but I'm not sure how to do this using client side JavaScript.
I tried searching JavaScript word count but I only get results on counting the total number of words, which is not what I'm looking for. What I am looking for is more keeping a count of each specific word. Can this be done in Javascript or Jquery? If so, how should I go about doing this?
Here is an approach for you
// first get an array of words
var words = text.split(' ');
// use Array.prototype.reduce (for example) to
// create statistics
var statistics = words.reduce(function (stat, word) {
if (!stat[word]) stat[word] = 0;
stat[word]++;
return stat;
}, {});
UPDATE: A little example which handles punctuation and upper/lower case, too: http://jsfiddle.net/1pnLzv8h/1/
Something like
var arra = ['ab','pq','mn','ab','mn','ab']
function wordCount(arra,val)
{
var ob={};
var len=arra.length;
for(var k=0;k<len;k++)
{
if(ob.hasOwnProperty(arra[k]))
{
ob[arra[k]]++;
continue;
}
ob[arra[k]]=1;
}
return ob[val];
}
alert(wordCount(arra,'ab')); //output 3

Object Obect array Json.stringify string array [closed]

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 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.

Extra tags on the end of a URL for different pages [closed]

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 9 years ago.
Improve this question
Hello I really want to learn how to do something like this. If you go to a page for example it says http://example.net/search.html?catagory=food&includelevelone=true. I do not have access to php so it can only be HTML and Javascript/jQuery. Thanks in advance!
The part of the URL that is from the questionmark onwards is called a query string.
Here is a pure JavaScript function to parse the query string to obtain particular values:
function querystring(key)
{
var filter;
var value;
key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
filter = new RegExp('[\\?&]' + key + '=([^&#]*)');
value = filter.exec(window.location.search);
if(value == null)
{
return '';
}
else
{
return decodeURIComponent(value[1].replace(/\+/g, ' '));
}
}
You just pass in the query string key name you're interested in (as a string) and you get the value back (also as a string.) An example of how you could use the function:
alert('Category = ' + querystring('catagory'));
Everything behind the questionmark is a url parameter. every word left of an equal sign is the name of the parameter, everything right of an equal sign is the corresponding value. The name-value-pairs are divided by &-signs
Here are two pages i quickly googled that are about getting these parameters in JavaScript (wich is really not that hard):
http://code-tricks.com/get-url-parameters-using-javascript
http://ziemecki.net/content/javascript-parsing-url-parameters

Categories

Resources